//
//  ChatInputView.swift
//  WeChatClient
//
//  Created by AI Assistant on 2025/10/31.
//

import SwiftUI

struct ChatInputView: View {
    @EnvironmentObject var chatViewModel: ChatViewModel
    @State private var showMoreActions = false
    
    var body: some View {
        VStack(spacing: 0) {
            // 主输入区域
            HStack(spacing: 8) {
                Button(action: {
                    chatViewModel.showEmojiPicker.toggle()
                    if chatViewModel.showEmojiPicker {
                        showMoreActions = false
                    }
                }) {
                    Image(systemName: chatViewModel.showEmojiPicker ? "keyboard" : "face.smiling")
                        .font(.system(size: 24))
                        .foregroundColor(.gray)
                }
                
                TextField("输入消息", text: $chatViewModel.newMessageText, axis: .vertical)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .lineLimit(1...4)
                
                if chatViewModel.newMessageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                    Button(action: {
                        showMoreActions.toggle()
                        if showMoreActions {
                            chatViewModel.showEmojiPicker = false
                        }
                    }) {
                        Image(systemName: "plus.circle")
                            .font(.system(size: 28))
                            .foregroundColor(.gray)
                    }
                } else {
                    Button(action: {
                        chatViewModel.sendMessage()
                    }) {
                        Image(systemName: "paperplane.circle.fill")
                            .font(.system(size: 28))
                            .foregroundColor(.green)
                    }
                }
            }
            .padding(.horizontal)
            .padding(.vertical, 8)
            
            // Emoji 选择器
            if chatViewModel.showEmojiPicker {
                EmojiPickerView()
                    .environmentObject(chatViewModel)
                    .transition(.move(edge: .bottom))
            }
            
            // 更多操作面板
            if showMoreActions {
                MoreActionsView(showMoreActions: $showMoreActions)
                    .environmentObject(chatViewModel)
                    .transition(.move(edge: .bottom))
            }
        }
        .background(Color(UIColor.systemBackground))
        .animation(.easeInOut(duration: 0.3), value: chatViewModel.showEmojiPicker)
        .animation(.easeInOut(duration: 0.3), value: showMoreActions)
    }
}

struct EmojiPickerView: View {
    @EnvironmentObject var chatViewModel: ChatViewModel
    @State private var selectedCategory = "笑脸"
    
    var body: some View {
        VStack(spacing: 0) {
            Divider()
            
            // 分类标签
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 20) {
                    ForEach(Array(chatViewModel.getEmojiCategories().keys), id: \.self) { category in
                        Button(action: {
                            selectedCategory = category
                        }) {
                            Text(category)
                                .font(.system(size: 14, weight: selectedCategory == category ? .medium : .regular))
                                .foregroundColor(selectedCategory == category ? .green : .gray)
                        }
                    }
                }
                .padding(.horizontal)
            }
            .padding(.vertical, 8)
            
            Divider()
            
            // Emoji 网格
            if let emojis = chatViewModel.getEmojiCategories()[selectedCategory] {
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 8), spacing: 15) {
                    ForEach(emojis, id: \.self) { emoji in
                        Button(action: {
                            chatViewModel.sendEmoji(emoji)
                        }) {
                            Text(emoji)
                                .font(.system(size: 28))
                        }
                    }
                }
                .padding()
            }
        }
        .frame(height: 240)
        .background(Color(UIColor.systemBackground))
    }
}

struct MoreActionsView: View {
    @EnvironmentObject var chatViewModel: ChatViewModel
    @Binding var showMoreActions: Bool
    
    let actions = [
        ("photo", "相册"),
        ("camera", "拍摄"),
        ("location", "位置"),
        ("phone", "语音通话"),
        ("video", "视频通话"),
        ("folder", "文件")
    ]
    
    var body: some View {
        VStack(spacing: 0) {
            Divider()
            
            LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 4), spacing: 20) {
                ForEach(Array(actions.enumerated()), id: \.offset) { index, action in
                    Button(action: {
                        handleAction(action.0)
                    }) {
                        VStack(spacing: 8) {
                            Image(systemName: action.0)
                                .font(.system(size: 24))
                                .foregroundColor(.white)
                                .frame(width: 50, height: 50)
                                .background(Color.gray.opacity(0.7))
                                .clipShape(RoundedRectangle(cornerRadius: 12))
                            
                            Text(action.1)
                                .font(.system(size: 12))
                                .foregroundColor(.primary)
                        }
                    }
                }
            }
            .padding(.horizontal, 20)
            .padding(.vertical, 20)
        }
        .frame(height: 200)
        .background(Color(UIColor.systemBackground))
    }
    
    private func handleAction(_ actionType: String) {
        switch actionType {
        case "photo":
            chatViewModel.showImagePicker = true
            showSampleImages()
        case "camera":
            showSampleImages()
        case "location":
            sendLocationMessage()
        default:
            print("Action: \(actionType)")
        }
        showMoreActions = false
    }
    
    private func showSampleImages() {
        let sampleImages = [
            "photo.on.rectangle.angled",
            "camera.macro",
            "photo.artframe",
            "photo.circle.fill",
            "camera.aperture",
            "photo.stack.fill",
            "camera.on.rectangle.fill",
            "photo.tv"
        ]
        if let randomImage = sampleImages.randomElement() {
            chatViewModel.sendImage(randomImage)
        }
    }
    
    private func sendLocationMessage() {
        let locationMessage = ChatMessage(
            content: "[位置] 北京市朝阳区",
            type: .text,
            senderId: User.currentUser.userName,
            senderName: User.currentUser.displayName
        )
        
        if let conversation = chatViewModel.currentConversation,
           let index = chatViewModel.conversations.firstIndex(where: { $0.id == conversation.id }) {
            chatViewModel.conversations[index].addMessage(locationMessage)
            chatViewModel.currentConversation = chatViewModel.conversations[index]
        }
    }
}
